package com.m7788.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.netease.LDNetDiagnoService.LDNetDiagnoListener;
import com.netease.LDNetDiagnoService.LDNetDiagnoService;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * Created by gxchen on 2018/5/23.
 */

public class NetDiagnosesUtil {

    private static String mDiagnoseLog = "";

    public static LDNetDiagnoService startDiagnoses(final Context context, final String domainAddress, LDNetDiagnoListener ldNetDiagnoListener, boolean baseData){
        LDNetDiagnoService _netDiagnoService = new LDNetDiagnoService(context.getApplicationContext(),
                getVersionCode(context)+"", getAppName(context), getVersionName(context), "huipang@corp.netease.com",
                getDeviceBrand()+"-"+getSystemModel(), domainAddress,getCarrier(context), getISOCountryCode(context),
                getMobileCountryCode(context), getMobileNetworkCode(context), ldNetDiagnoListener);
        _netDiagnoService.setIfUseJNICTrace(true);
        if(baseData){
            _netDiagnoService.execute("1");
        }else{
            _netDiagnoService.execute("0");
        }
        return _netDiagnoService;
    }

    public static void postDiagnoseData(final Context context){
        Observable.create(new Observable.OnSubscribe<JSONArray>(){

            @Override
            public void call(Subscriber<? super JSONArray> subscriber) {
                String result = HttpService.getInstance(context).isCheckNetWork();
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String isCheck = jsonObject.getString("is_check");
                    if(isCheck.equals("1")){
                        JSONArray jsonArray = jsonObject.getJSONArray("url");
                        if(jsonArray!=null){
                            subscriber.onNext(jsonArray);
                        }
                        subscriber.onCompleted();
                    }
                } catch (JSONException e) {
                    subscriber.onError(e);
                    subscriber.onCompleted();
                    e.printStackTrace();
                }
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<JSONArray>() {

            @Override
            public void onNext(JSONArray s) {
                if(s!=null){
                    mDiagnoseLog = "";
                    diagnose(context,s,-1,true);
                }
            }

            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable t) {
            }

        });
    }

    private static void diagnose(final Context context, final JSONArray jsonArray,final int pos , boolean isBaseData){
        if(jsonArray!=null){
            JSONObject daname = null;
            String domainName;
            final int count = jsonArray.length();
            try {
                if(pos>=0){
                    daname = jsonArray.getJSONObject(pos);
                    domainName = daname.getString("daname");
                }else{
                    domainName = "";
                }
                NetDiagnosesUtil.startDiagnoses(context, domainName, new LDNetDiagnoListener() {
                    @Override
                    public void OnNetDiagnoFinished(String log) {
                        mDiagnoseLog+=log;
                        if(pos == count - 1){
                           postDiagnoseData(mDiagnoseLog,context);
                        }else{
                            diagnose(context,jsonArray,pos+1,false);
                        }
                    }

                    @Override
                    public void OnNetDiagnoUpdated(String log) {
                    }
                },isBaseData);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private static void postDiagnoseData(final String log, final Context context) {
        Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("get_data",log);
                    jsonObject.put("flag","0");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                HttpService.getInstance(context).postNetDiagnoseData(jsonObject);
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(String s) {

            }
        });
    }

    /**
     * 获取应用程序名称
     */
    public static synchronized String getAppName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return context.getResources().getString(labelRes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * [获取应用程序版本名称信息]
     * @param context
     * @return 当前应用的版本名称
     */
    public static synchronized String getVersionName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * [获取应用程序版本名称信息]
     * @param context
     * @return 当前应用的版本名称
     */
    public static synchronized int getVersionCode(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取手机型号
     *
     * @return  手机型号
     */
    public static String getSystemModel() {
        return android.os.Build.MODEL;
    }

    /**
     * 获取手机厂商
     *
     * @return  手机厂商
     */
    public static String getDeviceBrand() {
        return android.os.Build.BRAND;
    }

    public static String getMobileCountryCode(Context context){
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String operator = tm.getNetworkCountryIso();
        String mcc = "";
        if(!TextUtils.isEmpty(operator)&&operator.length()>=3){
            mcc = operator.substring(3);
        }
        return mcc;
    }

    public static String getMobileNetworkCode(Context context){
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String operator = tm.getNetworkOperator();
        String mnc = "";
        if(!TextUtils.isEmpty(operator)&&operator.length()>=3){
            mnc = operator.substring(3);
        }
        return mnc;
    }

    public static String getISOCountryCode(Context context){
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        return tm.getSimCountryIso();
    }

    public static String getCarrier(Context context){
        String ProvidersName = "";
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String IMSI = tm.getSubscriberId();
        if( IMSI == null){
            return "unknow";
        }

        if(IMSI.startsWith("46000") || IMSI.startsWith("46002")){
            ProvidersName = "中国移动";
        }else if(IMSI.startsWith("46001")){
            ProvidersName = "中国联通";
        }else if (IMSI.startsWith("46003")) {
            ProvidersName = "中国电信";
        }
        return ProvidersName;
    }
}
